# -*- coding: utf-8 -*-
#*******************************************************************************
#   
#   https://nyaso.com/comic/xxxx.html 解析器                                          
#                                                                                         
#*******************************************************************************
from base import *

# 解析器标签
tag='nyaso'

#---------------------------- 验证模块 ----------------------------

# 每个解析模块都含有这个函数，用来判断链接是否符合该模块
def url_judgement(url):
    if re.match(r'https://nyaso.com/comic/\d+.html',url):
        return valid_check(url)
    return False

# 根据内容检测是否可解析
def valid_check(url):
    print('{} catch {} and valid test'.format(tag,url))
    content=request_for(url,common_headers)
    if content:
        content=content.decode('utf-8')
        if re.search(r'该漫画不存在',content):
            return False
        return get_loader(url)
    return content

# 下载器获取
def get_loader(url):
    return NyasoLoader(url,NyasoPageParser,NyasoVolParser)

#---------------------------- 下载器 ----------------------------

# 继承下载器部分
# 如果和基类一样，可以考虑不要
class NyasoLoader(ComicLoader):
    def __init__(self,url,comic_page_parser,comic_vol_parser):
        super().__init__(url,comic_page_parser,comic_vol_parser)

#---------------------------- 解析器 ----------------------------

class NyasoPageParser(ComicPageParser):
    def __init__(self,comic):
        super().__init__(comic)
    #
    def work(self,content):
        # title
        self.comic.title=re.compile(r'<h1>(.*?)</h1>',re.S|re.M).findall(content)[0].strip()
        # cover
        self.comic.cover=re.compile(r'</style><img src="(.*?)" style=',re.S|re.M).findall(content)[0].strip()
        # descripiton
        self.comic.description=re.compile(r'<pre><code>(.*?)</code></pre>',re.S|re.M).findall(content)[0].strip()
        # vols
        vols_content=re.compile(r'</h4>(.*?)</div>',re.S|re.M).findall(content)[0]
        urls=re.compile(r'href="(.*?)"',re.S|re.M).findall(vols_content)
        titles=re.compile(r'w">(.*?)<',re.S|re.M).findall(vols_content)
        vol_index=len(urls)
        for i in range(0,vol_index):
            self.comic.vols.append(InfoVol('https://nyaso.com/comic/'+urls[i],titles[i].strip()))
        self.comic.vols.reverse()

class NyasoVolParser(ComicVolParser):
    def __init__(self):
        super().__init__()
    #
    def work(self,content):
        pics_content=re.compile(r'<ul class="thumbs noscript">(.*)</ul>').findall(content)[0]
        self.feed(pics_content)
        self.pic_urls=self.pic_urls[:-1]
    
    def handle_starttag(self,tag,attrs):
        if tag=='a':
            infos={}
            for (v,k) in attrs:
                infos[v]=k
            self.pic_urls.append((infos['href'],zero_prefix(self.pic_index)))
            self.pic_index+=1

